package com.zhaojun.cloud.common.net;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * wwj
 * 2018/8/22  17:06
 */
public class HttpUtil {

    private final static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    public static String doPost(String url, List<NameValuePair> nvps) throws Exception {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        try {
            HttpPost httppost = new HttpPost(url);
            //添加HTTP POST参数
            logger.info("----------------------------------------");
            logger.info("请求网址" + httppost.getRequestLine().getUri());
            logger.info("请求参数" + JSONObject.toJSONString(nvps));
            logger.info("----------------------------------------");
            //将POST参数以UTF-8编码并包装成表单实体对象
            httppost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            //执行请求并获取结果
            HttpResponse httpResponse = httpclient.execute(httppost);
            HttpEntity entity = httpResponse.getEntity();
            String responseBody = new String(EntityUtils.toString(entity).getBytes("utf-8"));
            return responseBody;
        } finally {
            httpclient.close();
        }
    }

    public static String doGet(String url) throws Exception {
        return doGet(url, "");
    }


    public static String doGet(String url, String param) throws Exception {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        try {
            if (StringUtils.isNotBlank(param)) {
                url = url + "?" + param;
            }
            HttpGet httpGet = new HttpGet(url);
            //添加HTTP POST参数
            logger.info("----------------------------------------");
            logger.info("请求网址:" + httpGet.getRequestLine().getUri());
            logger.info("请求参数:" + param);
            logger.info("----------------------------------------");
            //将POST参数以UTF-8编码并包装成表单实体对象
            //执行请求并获取结果
            HttpResponse httpResponse = httpclient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            String responseBody = new String(EntityUtils.toString(entity).getBytes("utf-8"));
            return responseBody;
        } finally {
            httpclient.close();
        }
    }
}
